project(mirror_handle)

set(DOWNLOADS_DIR "${CMAKE_CURRENT_LIST_DIR}/../downloads")
# Remove the logs
file(GLOB DOWNLOAD_LOGS "${DOWNLOADS_DIR}/*.log")
file(REMOVE ${DOWNLOAD_LOGS})
# Glob all downloaded files
file(GLOB PACKAGES LIST_DIRECTORIES false "${DOWNLOADS_DIR}/*")
#message("all packages: ${PACKAGES}")
list(LENGTH PACKAGES PACKAGES_COUT)

set(CURR_COUNT 0)
set(UPDATED_PACKAGES)
set(RESULT_STRING "Result:\n")
foreach(PACKAGE ${PACKAGES})
    # Get file name
    get_filename_component(PACKAGE_NAME "${PACKAGE}" NAME)
    message("\r[${CURR_COUNT}\/${PACKAGES_COUT}] Checking ${PACKAGE_NAME}...")
    # Get file name length to skip renamed files
    string(LENGTH "${PACKAGE_NAME}" NAME_LENGTH)
    list(APPEND UPDATED_PACKAGES PACKAGE_NAME)
    # Add count
    math(EXPR CURR_COUNT "${CURR_COUNT} + 1")
    # Skip the renamed files
    if (NAME_LENGTH EQUAL 128)
        continue()
    endif()
    # Calculate the file hash -> file name
    file(SHA512 "${PACKAGE}" PACKAGE_SHA512)
    #message("SHA512 is: ${PACKAGE_SHA512}")
    set(PACKAGE_SHA512 "${DOWNLOADS_DIR}/${PACKAGE_SHA512}")
    if (NOT EXISTS "${PACKAGE_SHA512}")
        string(APPEND RESULT_STRING "copy ${PACKAGE} to ${PACKAGE_SHA512}\n")
        configure_file("${PACKAGE}" "${PACKAGE_SHA512}" COPYONLY)
    endif()
endforeach()

message("Special for 7zip.nuget...")
if (EXISTS "${DOWNLOADS_DIR}/a9dfaaafd15d98a2ac83682867ec5766720acf6e99d40d1a00d480692752603bf3f3742623f0ea85647a92374df405f331afd6021c5cf36af43ee8db198129c0")
    file(RENAME "${DOWNLOADS_DIR}/a9dfaaafd15d98a2ac83682867ec5766720acf6e99d40d1a00d480692752603bf3f3742623f0ea85647a92374df405f331afd6021c5cf36af43ee8db198129c0" "${DOWNLOADS_DIR}/8c75314102e68d2b2347d592f8e3eb05812e1ebb525decbac472231633753f1d4ca31c8e68
81a36144a8da26b2571305b3ae3f4e2b85fc4a290aeda63d1a13b8")
endif()
# Output to log
set(RESULT_FILE_CONTENT)
foreach(UPDATED_PACKAGE IN LISTS UPDATED_PACKAGES)
        string(APPEND RESULT_FILE_CONTENT "${UPDATED_PACKAGE}\n")
endforeach()
string(TIMESTAMP RESULT_FILE_NAME "update-result-%Y-%m-%d_%H:%M:%S.log")
file(WRITE RESULT_FILE_NAME "${RESULT_FILE_CONTENT}")

message("${RESULT_STRING}")
message("Done all packages.")